import socket
import optparse


def port_scan(ip, port):
    # socket 去连接看返回值
    try:
        s: socket = socket.socket()
        # 设置一个连接超时的时间
        s.settimeout(5)
        # connect_ex() 在连接失败时不会抛出异常，而是返回一个错误码。如果连接成功，则返回0（即没有成功）
        if s.connect_ex((ip, port)) == 0:
            print('[+] Host:{},Port:{},Status:OPEN'.format(ip, port))
        else:
            print('[+] Host:{},Port:{},Status:CLOSE'.format(ip, port))
    except Exception as e:
        print(e)
        pass
    finally:
        s.close()


def main():
    """
    命令解析、端口的扫描
    """
    parser = optparse.OptionParser('<Usage>')
    parser.add_option('-i', dest='string', help='target ip')
    parser.add_option('-p', '--port', dest='port', type='string', help='target port,可以用单个端口号，也可以用一个端口范围，比如：8000-9000')
    opts, args = parser.parse_args()
    ip = opts.ip
    port = opts.port
    if ip is None or port is None:
        print('请输入-h查看命令手册')
        return
    try:
        if '-' in port:
            start_port, end_port = port.split('-')
            for p in range(int(start_port), int(end_port)):
                port_scan(ip, p)
        else:
            port_scan(ip, int(port))
    except:
        print('请输入-h查看命令手册')


if __name__ == '__main__':
    main()
